/// 用户列表
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

import '../userlist/userlistitem.dart';

import '../../model/my_store.dart'; // 本地存储封装
import '../../model/config.dart'; // 全局配置文件

class UserList extends StatefulWidget {
  UserList({
    Key key,
    this.csid
  }):super(key: key);
  int csid;
  _UserListState createState() => _UserListState();
}

class _UserListState extends State<UserList> with AutomaticKeepAliveClientMixin {
  List userList; // 客服信息
  @override
  void initState () {
    userList = [];
    getUserList();
    super.initState();
  }
  void getUserList () {
    // 获取用户消息列表
    var LocaUserList = MyStore().getData('ALLUSER${widget.csid}');
    var MsgUserList = LocaUserList != null ? LocaUserList['list'] : null;
    if (MsgUserList == null) {
      // 本地存储没有消息列表，从服务器获取
      Dio().get(
        MyConfig().baseurl + '/csuser/getalluser',
        data: {
          'butt_id' : widget.csid
        }
      ).then((response) {
        if (response.statusCode == 200 && response.data['status'] == 1) {
          setState(() {userList = [];});
          response.data['msg'].forEach((item) { setState(() { userList.add(item); }); });
          MyStore().setData('ALLUSER${widget.csid}', {
            'list': userList
          });
        } else {
          setState(() {userList = [];});
        }
      }).catchError((err) {
        setState(() {userList = [];});
      });
    } else {
      setState(() {userList = MsgUserList;});
    }
  }
  @override

  Widget renderMsgList () {
    if (userList.length <= 0 ) {
      return Center(
        child: Text('加载中')
      );
    } else {
      return ListView.builder(
        itemCount: userList.length,
        itemBuilder: (BuildContext context, int index) {
          return UserListItem(
            msgUser: userList[index],
            onClick: () {
              
            }
          );
        },
      );
    }
  }

  Widget build(BuildContext context) {
    return Container(
      child: renderMsgList(),
    );
  }
  @protected
  bool get wantKeepAlive => true;
}